#pragma once
// 这是一个封装mutex的代码

#include <iostream>
#include <pthread.h>
#include <mutex>
#include <string>
namespace MutexModel
{
    class Mutex
    {
    public:
        Mutex()
        {
            // 初始化
            int n = pthread_mutex_init(&_mutex, nullptr);
            if (n != 0)
            {
                std::cerr << "init false" << std::endl;
            }
        }
        void Lock()
        {
            int n = pthread_mutex_lock(&_mutex);
            if (n != 0)
            {
                std::cerr << "lock false" << std::endl;
            }
        }
        void UnLock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            if (n != 0)
            {
                std::cerr << "unlock false" << std::endl;
            }
        }
        pthread_mutex_t *GetMutex()
        {
            return &_mutex;
        }
        pthread_mutex_t& Get()
        {
            return _mutex;
        }
        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_mutex);
            if (n != 0)
            {
                std::cerr << "destroy false" << std::endl;
            }
        }

    private:
        pthread_mutex_t _mutex;
    };

    // RAII管理锁
    class Steward
    {
    public:
        Steward(Mutex &mutex) : _mutex(mutex)
        {
            _mutex.Lock();
        }
        ~Steward()
        {
            _mutex.UnLock();
        }

    private:
        Mutex &_mutex;
    };
}